#include "pwmcontrol.h"

PwmControl* PwmControl::pwmcon = nullptr;

PwmControl *PwmControl::instance()
{
    if(PwmControl::pwmcon == nullptr)
        PwmControl::pwmcon = new PwmControl();
    return PwmControl::pwmcon;
}

bool PwmControl::initPwm()
{
    QString exportPath = QString("/sys/class/pwm/pwmchip%1/export").arg(2);
    if (!writeToFile(exportPath, QString::number(0))) {
        qDebug() << "Failed to export PWM channel" << 0;
        return false;
    }
    // 等待设备创建
      QTimer::singleShot(100, [this]() {
          // 设置PWM参数
          QString periodPath = m_basePath + "period";
          QString dutyCyclePath = m_basePath + "duty_cycle";

          // 设置周期为20ms (20000000纳秒) - 舵机标准周期
          if (!writeToFile(periodPath, "20000000")) {
              qDebug() << "Failed to set period";
              return;
          }

          // 初始占空比为1ms (1000000纳秒) - 中间位置
          if (!writeToFile(dutyCyclePath, "1000000")) {
              qDebug() << "Failed to set initial duty cycle";
              return;
          }

          m_initialized = true;
          qDebug() << "PWM initialized successfully";
      });

      return true;
}

bool PwmControl::writeToFile(const QString &path, const QString &value)
{
    QFile file(path);
       if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
           qDebug() << "Cannot open file:" << path;
           return false;
       }

       QTextStream out(&file);
       out << value;
       file.close();

       return true;
}


bool PwmControl::setPulseWidth(int pulseWidthUs)
{
    if (!m_initialized) {
        qDebug() << "PWM not initialized";
        return false;
    }

    // 将微秒转换为纳秒
    int dutyCycleNs = pulseWidthUs * 1000;

    QString dutyCyclePath = m_basePath + "duty_cycle";
    return writeToFile(dutyCyclePath, QString::number(dutyCycleNs));
}

bool PwmControl::setAngle(int angle)
{
    // 限制角度范围
    angle = qBound(0, angle, 180);

    // 舵机角度转换：0°=1ms, 90°=1.5ms, 180°=2ms
    // 公式：pulseWidth(us) = 1000 + (angle / 180.0) * 1000
    int pulseWidthUs = 1000 + (angle / 180.0) * 1000;

    return setPulseWidth(pulseWidthUs);
}
bool PwmControl::enable()
{
    if (!m_initialized) {
        qDebug() << "PWM not initialized";
        return false;
    }

    QString enablePath = m_basePath + "enable";
    return writeToFile(enablePath, "1");
}
PwmControl::PwmControl()
{
     m_basePath = QString("/sys/class/pwm/pwmchip%1/pwm%2/").arg("pwm").arg(0);
}
